package com.local.web.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.local.web.constants.CaptchaTypeEnum;
import com.local.web.constants.WebConstants;
import com.local.web.util.CommonUtil;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.PrintWriter;
import java.util.Objects;

@Component
public class WebInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HttpSession session = request.getSession();
        //查询session是否保存了User用户对象信息
        Object loginUser = session.getAttribute(WebConstants.WEB_USER_SESSION_KEY);
        if (Objects.isNull(loginUser)) { //
            if (CommonUtil.isAjaxRequest(request)) {
                response.setCharacterEncoding("utf-8");
                response.setContentType("application/json; charset=utf-8");
                PrintWriter writer = response.getWriter();
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("code", 201);
                jsonObject.put("message", "请先登录");
                writer.write(jsonObject.toJSONString());
                writer.flush();
                writer.close();
            } else {
                response.sendRedirect(request.getContextPath() + "/login");
            }
            return false;
        } else {
            return true;
        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
